<?php

namespace Dls\Entity\V0\Grid;

use Dls\Entity\V0\Grid;
use Dls\Entity\V0\Grid\Outputs\AbstractOutput;
use Dls\Entity\V0\Grid\Outputs\AjaxOutput;

class Output
{
    const SCOPE_ALL = 'all';
    /**
     *
     * @var
     */
    public static $queryName = '_list_';

    /**
     * @var Grid
     */
    protected $grid;
    /**
     * Available exporter drivers.
     *
     * @var array
     */
    protected static $drivers = [];

    /**
     * Create a new Exporter instance.
     *
     * @param Grid $grid
     */
    public function __construct(Grid $grid)
    {
        $this->grid = $grid;
    }

    /**
     * Resolve export driver.
     *
     * @param string $driver
     *
     * @return AbstractOutput
     */
    public function resolve($driver)
    {
        if ($driver instanceof Grid\Outputs\AbstractOutput) {
            return $driver->setGrid($this->grid);
        }
        return $this->getOutput($driver);
    }
    /**
     * Get export driver.
     *
     * @param string $driver
     *
     * @return AjaxOutput
     */
    protected function getOutput($driver)
    {
        if (!array_key_exists($driver, static::$drivers)) {
            return $this->getDefaultOutput();
        }
        return new static::$drivers[$driver]($this->grid);
    }
    /**
     * Get default exporter.
     *
     * @return AjaxOutput
     */
    public function getDefaultOutput()
    {
        return new AjaxOutput($this->grid);
    }

    /**
     * 格式化查询条件
     * example 1：
     * ['user_id', 'created_time'] => user_id=<{user_id}>&created_time=<{created_time}>
     *
     * example 2:
     *  ['user_id', ['type' => 'value']] => user_id=<{user_id}>&<{type}>=<{value}>
     *
     * @param array $queryConditions
     * @return string
     */
    public static function formatQuery(array $queryConditions)
    {
        $query[self::$queryName] = self::SCOPE_ALL;

        foreach ($queryConditions as $condition) {
            if (is_array($condition)) { //
                $key = key($condition);
                $query["<{{$key}}>"] = "<{{$condition[$key]}}>";
            } else {
                $query[$condition] = "<{{$condition}}>";
            }
        }

        return urldecode(http_build_query($query));
    }

}